<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row
        type="flex"
        justify=""
      >
        <el-col :span="6">
          <el-button
            type="primary"
            @click='addRoleDialogVisible=true'
          >
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table
        :data="roleList"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <!-- 属性权限列表 -->
          <template v-slot='{row}'>
            <div>
              <el-row
                type="flex"
                align="middle"
                class='bdbottom'
                :class="{'bdtop':index==0}"
                v-for="(item, index) in row.children"
                :key="item.id"
              >
                <el-col :span="5">
                  <el-tag
                    type="danger"
                    closable
                    @close='removeRoleById(row,item.id)'
                  >{{item.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <el-row
                    type="flex"
                    align="middle"
                    v-for="(item1, index1) in item.children"
                    :key="item1.id"
                    :class="{'bdtop':index1!==0}"
                  >
                    <el-col :span="8">
                      <el-tag
                        type="success"
                        closable
                        @close='removeRoleById(row,item1.id)'
                      >
                        {{ item1.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="16">
                      <el-tag
                        type="warning"
                        v-for="item2 in item1.children"
                        :key="item2.id"
                        @close='removeRoleById(row,item2.id)'
                        closable
                      >
                        {{ item2.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <!-- <el-row
                :class="(index==0?'':'bdbottom')"
                v-for='(item,index) in row.children'
                :key="item.id"
                type="flex"
                align='middle'
              >
                <el-col :span="6">
                  <el-tag
                    type="danger"
                    closable
                  >{{item.authName}}</el-tag>
                  <i class='el-icon-caret-right'></i>
                </el-col>
                <el-col :span="18">
                  <el-row
                    type="flex"
                    align='middle'
                    :class="(index1==0?'':'bdtop')"
                    v-for="(item1,index1) in item.children"
                    :key="item1.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                      >
                        {{item1.authName}}
                      </el-tag>
                      <i class='el-icon-caret-right'></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        type="warning"
                        v-for="item2 in item1.children"
                        :key="item2.id"
                        closable
                        @close='removeRoleById(row,item2.id)'
                      > 

                        {{item2.authName}}
                      </el-tag>

                    </el-col>
                  </el-row>
                </el-col>
              </el-row>-->
            </div>
          </template>

        </el-table-column>

        <el-table-column
          type='index'
          label="#"
        >
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="400px"
        >
          <template v-slot='{row}'>
            <div>
              <el-button
                type="danger"
                icon="el-icon-edit"
                @click="getRoleById(row.id)"
              >编辑</el-button>
              <el-button
                icon="el-icon-delete"
                type="primary"
                @click="deleteRole(row.id)"
              >删除</el-button>
              <el-button
                icon="el-icon-star-off"
                type="success"
                @click='showSetRightDialog(row)'
              >分配权限</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="30%"
      @close='resetField'
    >
      <el-form
        :model="addRoleForm"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addRole"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="30%"
      @close='resetEditForm'
    >
      <el-form
        :model="editRoleForm"
        ref="editRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editRoleDialogVisible = false">取 消 </el-button>
        <el-button
          type="primary"
          @click="editRole(editRoleForm.roleId)"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限树形列表-->
    <el-dialog
      title="权限分配"
      :visible.sync="setRIghtDialogVisible"
      width="30%"
    @close='handleDialogClose()'
    >
      <el-tree
  :data="rightsList"
  show-checkbox
  node-key="id"
  :props='defaultProps'
  :default-expand-all='true'
 :default-checked-keys="defkeys"
 ref="tree"
  >
</el-tree>
  <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRIghtDialogVisible = false">取 消 </el-button>
        <el-button
          type="primary"
          @click="setRIghts()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: [],
  data () {
    return {
      // 角色列表
            roleList:[],
      //  ------------------------------ 添加角色数据----------
      addRoleDialogVisible:false,
      // 添加角色表单
      addRoleForm:{
        roleName:'',
        roleDesc:''
      },
      // --------------编辑角色数据--------------- 
      editRoleDialogVisible:false,
  // 编辑角色表单 
        // 添加角色表单
      editRoleForm:{
        roleName:'',
        roleDesc:''
      },
      // ------------分配权限数据--------------  ·
      setRIghtDialogVisible:false,
      // 所有权限列表
      rightsList:[],
      // 树形控件配置
      defaultProps:{
        children:'children',
        label:'authName'
      },
      // 默认选中项
      defkeys:[],
      // 角色id
      roleId:''

    }   
  }
  ,created(){
        this.getRoleList();
        
    },
  mounted () {

  },
  methods: {
    // 获取角色列表
 async   getRoleList(){

      const { data: res } = await this.$http.get('roles');
      if(res.meta.status !== 200){ return this.$message.error('获取角色列表失败!')}
      this.roleList = res.data
      console.log(res.data[0]);
    },
    // ----------------添加角色功能----------------
  async addRole(){
    const { data: res } = await this.$http.post('roles', this.addRoleForm)
    if(res.meta.status !== 201){ return this.$message.error('添加角色失败')}
    this.$message.success('添加角色成功')
    this.addRoleDialogVisible=false
    this.getRoleList()
  },
  resetField(){
    this.$refs.addRoleFormRef.resetFields()
 
  },
// --------------编辑角色功能-------------------
async getRoleById(id){
  const { data: res } = await this.$http.get('roles/'+id)
    if(res.meta.status !== 200){return this.$message.error('获取角色失败')}
  this.editRoleForm=res.data
     this.editRoleDialogVisible=true
},
async editRole(id){
    const { data: res } = await this.$http.put('roles/'+id,this.editRoleForm)
    if(res.meta.status !==200){ return this.$message.error('修改用户失败')}
    this.$message.success('修改用户成功!')
  this.editRoleDialogVisible=false
  this.getRoleList()
  },
  resetEditForm(){
    this.$refs.editRoleFormRef.resetFields()
  },
  //---------------------------------- 删除功能
  deleteRole(id){
    this.$confirm('确认删除?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      callback:async action => {
        if(action === 'confirm'){
const { data: res } = await this.$http.delete('roles/'+id)
if(res.meta.status!==200){ return this.$message.error('删除角色失败')}
this.$message.success('删除角色成功')
this.getRoleList()

        }else {
          this.$message.info('取消删除操作')
        }
      }
    })
    
  },
  //------------------------------- 删除权限功能
  removeRoleById(role,qxId){

   this.$confirm('确认删除?', '警告', {
     confirmButtonText: '确定',
     cancelButtonText: '取消',
     type: 'warning',
     callback:async action => {
       if(action === 'confirm'){
         const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${qxId}`)
        //  console.log(res);
        if(res.meta.status !== 200){ return this.$message.error('权限取消失败')}
        this.$message.success('权限取消成功')
      role.children = res.data
       }else{
         this.$message.info('操作取消')
       }
     }
   })
   
  },
  // -------------------------分配权限功能--------------------
  // 展示分配权限对话框
  async showSetRightDialog(role){
    const { data: res } = await this.$http.get('rights/tree')
      // console.log(res);
      if(res.meta.status !== 200){ return this.$message.error('获取权限列表失败')}
      this.rightsList = res.data
      // 默认显示的权限数组
      this.getDefaultkeys(role,this.defkeys)
      this.roleId=role.id
    this.setRIghtDialogVisible=true
    },

    // 获得权限数组
  getDefaultkeys(role,arr){
    // 如果里面有children就循环下去
    if(role.children){
      role.children.forEach(t=>this.getDefaultkeys(t,arr))
    }else{
      // 如果没有children了说明是三级权限
      // console.log(role.id);
      // 把所有三级权限的id存入数组
      arr.push(role.id)
    }
  },
  // 关闭dialog清空默认权限数组
  handleDialogClose(){
    this.defkeys=[]
  },
  // 分配权限确认 
    async  setRIghts(){
      console.log(this.$refs);
      // console.log(this.defkeys);
      let rids = [...this.$refs.tree.getCheckedKeys(),...this.$refs.tree.getHalfCheckedKeys()]
        rids = rids.join(",")
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:rids
      })
      console.log(res);
      if(res.meta.status !== 200){ return this.$message.error('权限分配失败')}
      this.getRoleList()
      this.setRIghtDialogVisible = false
    },
  }

}

</script>
<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdbottom{
border-bottom: 1px solid #eee;
}
.bdtop{
border-top: 1px solid #eee;
}
</style> 